package com.ming.elm.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter("/*")
public class SessionCheck implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        // 获取客户端请求路径
        String path = req.getServletPath();
        // 获取方法字符串
        // String className = path.substring(1,path.lastIndexOf("/"));
        String methodName = path.substring(path.lastIndexOf("/")+1);
        // 如果需要登录
        if(!methodName.equals("getUserByIdByPass")
        && !methodName.equals("listBusinessByOrderTypeId")
        && !methodName.equals("listCart")
        && !methodName.equals("getBusinessById")
        && !methodName.equals("listFoodByBusinessId")
        && !methodName.equals("saveUser")
        && !methodName.equals("logOut")
            ){
            // 获取用户session
            HttpSession session = req.getSession();
            String userId = (String) session.getAttribute("userId");
            System.out.println("SessionCheck-userId:"+userId);
            // 如果没有该用户的session存在,则返回 not log
            if(userId==null){
                PrintWriter writer = resp.getWriter();
                writer.print("not log");
                writer.close();
            }
        }
        chain.doFilter(request,response);
    }
}
